package x;

import x.minigame1.bottle;
import x.minigame1.level;
import java.awt.event.*;
import javax.swing.*;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.awt.*;
import java.util.*;
import java.awt.image.BufferStrategy;



public class Minigame1 extends Canvas implements MouseListener, ActionListener {

        private int score;
        private Sound gunshot_miss;
        private int randomx;
        private int randomy;
        private BufferStrategy strategy;
        private level level;
        Frame frame;
        private Random generator = new Random();
        Graphics2D g;
        private int timeleft;
        private Thread timer_thread;
        private boolean gameRunning;
        private int currentBottle;
        private bottle[] bottles;
        private Counter counter;

        public Minigame1() {
            //initliaize some variables
                score = 0;
                gunshot_miss = new Sound("src/x/minigame1/gunshot_miss.wav");
                timeleft = 30;
                timer_thread = new Thread();
                timer_thread.start();
                gameRunning = true;
                currentBottle = -1;
                counter = new Counter();



                // implement frame.
                frame = new Frame("Shooting Range Minigame");

                setBounds(5,5,840,640);
                frame.add(this);
                frame.setSize(840,640);
                frame.setResizable(true);
                frame.setVisible(true);
                frame.setLocationRelativeTo(null);




                // exit game source
                frame.addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {
                        frame.setVisible(false);
                        frame.dispose();}});


               //mouse listener
                frame.addMouseListener(this);
                addMouseListener(this);



                //buffer
                createBufferStrategy(2);
                strategy = getBufferStrategy();

                // level
               level = new level();
               //this function initalizes the array of bottle targets
               initializeBottle();

              //loop to display playing instructions for thread.sleep milliseconds
              Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
             // instructions(g);
              strategy.show();
             // try{timer_thread.sleep(5000);}catch (Exception e){};
              g.dispose();


              //randomly setup the first bottle
              currentBottle = generator.nextInt(5);
              bottles[currentBottle].activate();

             // start the game loop
              startGame();

          //after the game is over, paint the final score
          g = (Graphics2D) strategy.getDrawGraphics();
          display_score(g);
          strategy.show();
          g.dispose();





                //the close game button
                Button button = new Button("Exit Game");
                button.addActionListener(this);
                frame.add(button);
                frame.setLayout(new BoxLayout(frame, BoxLayout.PAGE_AXIS));






        }

//game loop
        public void startGame() {
            //begin the timer
              counter.start();
                while (gameRunning) {
               gameRunning = Count();

                        Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
                        g.setColor(Color.white);
                        g.fillRect(0,0,840,600);
     //painting all the different objects.  the bottles must be painted as an array
           level.paint(g);
           // for (int i = 0; i < bottles.length; i++)
                 //bottles[i].paint(g);
           bottles[currentBottle].paint(g);
            paint(g);
                        g.dispose();
                        strategy.show();
                        // system pausing
                        try { Thread.sleep(4); } catch (Exception e) {};
                }


            //after the game has ended, disable all targets
             for (int i = 0; i < bottles.length; i++)
             {
          Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
          g.setColor(Color.white);
          g.fillRect(0,0,840,600);
          bottles[i].activated = false;
          bottles[i].paint(g);
          g.dispose();
          strategy.show();
            }

	


    }

   //this is the function that listens for the click to exit the program
        public void actionPerformed(ActionEvent a) {

            int result = JOptionPane.showConfirmDialog(null,"Times up! Play again? Your score was: " + score  ,"Good Job!!!" , 	      	 	 JOptionPane.YES_NO_OPTION);
        if(result == JOptionPane.NO_OPTION) // if canceled
        {
             frame.setVisible(false);
             frame.dispose();
        }

        }


        public void initializeBottle(){
            //initilize the array
            bottles = new bottle[5];
            //assignment of bottle targets and locations
            //upper row, from left to right
            bottles[0] = new bottle(level, 10, 10);
            bottles[1] = new bottle(level, 40, 10);
            bottles[2] = new bottle(level, 70, 10);
            //middle row from left to right
            bottles[3] = new bottle(level, 25, 30);
            bottles[4] = new bottle(level, 55, 30);


        }

        public boolean Count(){
            if (counter.getTimeSecs() != 30)
                return true;
            else
            {
                counter.stop();
                return false;
            }
                        }


    public void mouseEntered(MouseEvent e) {
   //set crosshair cursor
   //this is the coordinate of the exact middle of the crosshair
final Point middle = new Point(16,16);
final Image cursorImage = new ImageIcon("src/x/minigame1/crosshair.png").getImage();
Toolkit toolkit = Toolkit.getDefaultToolkit();
Cursor c = toolkit.createCustomCursor(cursorImage , middle, "crosshair");
frame.setCursor (c);
    }


    public void mouseClicked(MouseEvent e)
 {
        //the temp variable  is used so that the bottle does not
        //come on at the same location twice in a row
        int nextBottle;

       gunshot_miss.play();
       //cycle through array of targets and check for hit
       //if a hit is returned, the bottle is deactivated
       //a new bottle is generated and the current bottle becomes the old one
       //the while loop prevents bottles from appearing at the same spot twice in a row
       for (int i = 0; i < bottles.length; i++)
        {
      if(bottles[i].activated)
             {
                if (bottles[i].checkHit(e.getX(), e.getY())){
                score++;
                nextBottle = generator.nextInt(5);
                while (nextBottle == currentBottle)
                    nextBottle = generator.nextInt(5);
                currentBottle = nextBottle;
                bottles[currentBottle].activate();}
             }
        }
  }

    //these three are not used but they are required for the program to compile
    public void mousePressed(MouseEvent e) {
    }
    public void mouseReleased(MouseEvent e) {
    }
    public void mouseExited(MouseEvent e) {
    }

    //this is the timer
  public void paint(Graphics2D g) {
            //the score box
            g.setColor(Color.red);
            g.draw3DRect(600, 50, 150, 50, true);
            g.fill3DRect(600, 50, 150, 50, true);
            g.setColor(Color.black);
            g.drawString("Score", 620, 70);
         //the score integer must be converted into a string before being output
            g.drawString(Integer.toString(score), 620, 90);

           //the timer box
            g.setColor(Color.red);
            g.draw3DRect(400, 50, 150, 50, true);
            g.fill3DRect(400, 50, 150, 50, true);
            g.setColor(Color.black);
            g.drawString("Time Left", 420, 70);
         //the time must be subtracted from elapsed and converted to a string
            //g.drawString(Integer.toString(timeleft), 420, 90);
           long seconds = 30 -  counter.getTimeSecs();
            g.drawString(Long.toString(seconds), 420, 90);
        }


  public void instructions(Graphics2D g){
            g.setColor(Color.black);
            g.drawString("Directions for playing will go here", (level.WIDTH/2) * 10, (level.HEIGHT/2) * 10);

  }


   public void display_score(Graphics2D g){
      g.setColor(Color.black);
      g.drawString("Score: " + Integer.toString(score),(level.WIDTH/2) * 10, (level.HEIGHT/2) * 10);

   }

}
